const db = require("./core");
const dayjs = require("dayjs");
const { post } = require("../routes/users");

module.exports = {
  async findOneUser(query) {
    const user = await db.findOne("user", query);
    user && delete user.password;
    return user;
  },

  addOneUser(user) {
    return db.insertOne("user", user);
  },
  // 添加文章
  addOnePost(post) {
    return db.insertOne("ArticleDetails", post);
  },
  // 找到一篇文章
  async findOnePost(query) {
    const post = await db.findOne("ArticleDetails", query);
    if (post) {
      // 找到文章作者的详细信息
      const user = await module.exports.findOneUser({
        _id: post.authorId,
      });
      post.author = user;
      post.created = dayjs(post._id.getTimestamp()).format(
        "YYYY-MM-DD HH:mm:ss"
      );
    }
    return post; // authorId
  },
  async updateOnePost(query, data) {
    return db.updateOne("ArticleDetails", query, data);
  },

  //   找到多篇文章
  // 查找文章的方法 query 对象 查询的条件   第二参数传一个对象
  async findPost(query = {}, { limit = 5, skip = 0 } = {}) {
    const count = await db.count("ArticleDetails"); // 获取文章的总数量
    const posts = await db.findMany("ArticleDetails", query, limit, skip); // [{},{},{}]

    posts.forEach((post) => {
      post.created = dayjs(post._id.getTimestamp()).format(
        "YYYY-MM-DD HH:mm:ss"
      );
    });

    return {
      // ~按位（二进制位）取反，~~两个波浪线 用于取整
      count,
      limit,
      skip,
      page: ~~(skip / limit),
      posts,
    };
  },
};

async function test() {
  console.log(
    await module.exports.findPost(
      {
        title: "123",
      },
      {
        skip: 20,
        limit: 5,
      }
    )
  );
}
